import { beforeHttp, afterHttp } from 'src/plugins/http/interceptor';
import { UtilTools, hideLoading, showLoading, } from 'src/plugins/utils';
import config from 'src/config';

const { appkey } = config
let requestTask = null;

export default opt => {
	opt = opt || {};
	opt.timeout = opt.timeout || 1000 * 60;
	opt.data = opt.data || {};
	opt.header = UtilTools.extend(opt.header || {});
	opt.method = opt.method ? opt.method.toUpperCase() : 'POST';
	return new Promise((resolve, reject) => {
		beforeHttp(opt).then(opt => {
			opt.header.loading = opt.header.loading || {};
			if (opt.header.loading.show == undefined) {
				opt.header.loading.show = true;
			}
			if (opt.header.loading.show) {
				showLoading({
					'title': opt.header.loading.title || '拼命加载中...',
					'mask': opt.header.loading.mask || true
				});
			}
			requestTask = uni.request({
				'url': opt.url,
				'method': opt.method,
				'data': opt.data,
				'header': opt.header,
				'dataType': opt.dataType || 'JSON',
				'timeout': opt.timeout,
				// #ifdef H5
				'withCredentials': true,
				// #endif
				// responseType:opt.responseType,
				success(result) {
					afterHttp(result).then(res => {
						resolve(res);
					}).catch(err => {
						reject(err);
					});
				},
				fail(err) {
					reject(err);
				},
				complete(res) {
					if (opt.header.loading.show) {
						hideLoading();
					}
				}
			});
		}).catch(err => {
			reject(err);
		});
	});
};